package com.lsa.shenn.common.perm;

import com.lsa.helpers.Utils;

public class PermNoRepeat
{
	private int n;

	public PermNoRepeat(int n)
	{
		this.n = n;
	}
	
	public int[] createFirstSequence()
	{
		int[] seq = new int[this.n];
		
		for (int i = 0; i < seq.length; i++)
		{
			seq[i] = i+1;
		}
		
		return seq;
	}
	
	public int[] move2NextSequence(int[] seq )
	{
		if (seq == null)
		{
			return createFirstSequence();
		}
		
		if (this.n < 2)
		{
			return seq;
		}
		
		int k = n - 2;
		
		while(k > -1 && seq[k] > seq[k+1])
		{
			--k;
		}
		
		if (k == -1)
			return null;
		
		int t = k + 1;
		
		while(t < n - 1 && seq[t+1] > seq[k])
		{
			t = t + 1;
		}
		
		int tmp = seq[t];
		seq[t] = seq[k];
		seq[k] = tmp;
		
		Utils.reverseArrayPart(seq, k+1, seq.length - (k+1));
		return seq;
	}
}
